<template>
  <div class="monitor-container fade-in">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <Monitor />
            </el-icon>
            系统监控
          </h2>
          <p class="page-subtitle">实时监控系统性能、服务器状态和资源使用情况</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button type="success" @click="exportReport">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
          <el-button type="warning" @click="configureAlerts">
            <el-icon><Setting /></el-icon>
            告警配置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 系统状态概览 -->
    <div class="status-overview">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="status-card" shadow="hover">
            <div class="status-content">
              <div class="status-icon" :class="systemStatus.status">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">系统状态</div>
                <div class="status-value">{{ systemStatus.status === 'healthy' ? '正常' : '异常' }}</div>
                <div class="status-desc">{{ systemStatus.message }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="status-card" shadow="hover">
            <div class="status-content">
              <div class="status-icon" :class="cpuStatus.status">
                <el-icon><Cpu /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">CPU使用率</div>
                <div class="status-value">{{ cpuStatus.usage }}%</div>
                <div class="status-desc">{{ cpuStatus.message }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="status-card" shadow="hover">
            <div class="status-content">
              <div class="status-icon" :class="memoryStatus.status">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">内存使用率</div>
                <div class="status-value">{{ memoryStatus.usage }}%</div>
                <div class="status-desc">{{ memoryStatus.message }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="status-card" shadow="hover">
            <div class="status-content">
              <div class="status-icon" :class="diskStatus.status">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">磁盘使用率</div>
                <div class="status-value">{{ diskStatus.usage }}%</div>
                <div class="status-desc">{{ diskStatus.message }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 实时性能图表 -->
    <div class="performance-charts">
      <el-row :gutter="24">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>CPU使用率趋势</h3>
                <div class="chart-controls">
                  <el-select v-model="cpuTimeRange" size="small" style="width: 120px">
                    <el-option label="最近1小时" value="1h" />
                    <el-option label="最近6小时" value="6h" />
                    <el-option label="最近24小时" value="24h" />
                  </el-select>
                </div>
              </div>
            </template>
            <v-chart class="chart" :option="cpuChartOption" autoresize />
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>内存使用率趋势</h3>
                <div class="chart-controls">
                  <el-select v-model="memoryTimeRange" size="small" style="width: 120px">
                    <el-option label="最近1小时" value="1h" />
                    <el-option label="最近6小时" value="6h" />
                    <el-option label="最近24小时" value="24h" />
                  </el-select>
                </div>
              </div>
            </template>
            <v-chart class="chart" :option="memoryChartOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 网络和磁盘监控 -->
    <div class="network-disk-monitor">
      <el-row :gutter="24">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>网络流量监控</h3>
                <el-tag type="info">{{ networkStatus.connections }} 个连接</el-tag>
              </div>
            </template>
            <v-chart class="chart" :option="networkChartOption" autoresize />
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>磁盘I/O监控</h3>
                <el-tag type="info">{{ diskIOStatus.totalIO }} IO/s</el-tag>
              </div>
            </template>
            <v-chart class="chart" :option="diskIOChartOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 服务状态和进程监控 -->
    <div class="services-processes">
      <el-row :gutter="24">
        <el-col :xs="24" :lg="12">
          <el-card class="service-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>服务状态</h3>
                <el-button type="primary" size="small" @click="refreshServices">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            <div class="service-list">
              <div 
                v-for="service in services" 
                :key="service.name" 
                class="service-item"
                :class="service.status"
              >
                <div class="service-info">
                  <div class="service-name">{{ service.name }}</div>
                  <div class="service-desc">{{ service.description }}</div>
                </div>
                <div class="service-status">
                  <el-tag :type="getServiceTagType(service.status)" size="small">
                    {{ getServiceStatusLabel(service.status) }}
                  </el-tag>
                  <div class="service-uptime">{{ service.uptime }}</div>
                </div>
                <div class="service-actions">
                  <el-button 
                    size="small" 
                    :type="service.status === 'running' ? 'warning' : 'success'"
                    @click="toggleService(service)"
                  >
                    {{ service.status === 'running' ? '停止' : '启动' }}
                  </el-button>
                  <el-button size="small" @click="viewServiceLogs(service)">
                    日志
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="process-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>进程监控</h3>
                <el-input
                  v-model="processSearch"
                  placeholder="搜索进程"
                  size="small"
                  style="width: 200px"
                  clearable
                />
              </div>
            </template>
            <div class="process-list">
              <div 
                v-for="process in filteredProcesses" 
                :key="process.pid" 
                class="process-item"
              >
                <div class="process-info">
                  <div class="process-name">{{ process.name }}</div>
                  <div class="process-pid">PID: {{ process.pid }}</div>
                </div>
                <div class="process-metrics">
                  <div class="metric">
                    <span class="metric-label">CPU:</span>
                    <span class="metric-value">{{ process.cpu }}%</span>
                  </div>
                  <div class="metric">
                    <span class="metric-label">内存:</span>
                    <span class="metric-value">{{ process.memory }}MB</span>
                  </div>
                </div>
                <div class="process-actions">
                  <el-button size="small" type="danger" @click="killProcess(process)">
                    终止
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 告警信息 -->
    <div class="alerts-section">
      <el-card class="alerts-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>系统告警</h3>
            <div class="alert-controls">
              <el-button type="primary" size="small" @click="acknowledgeAllAlerts">
                全部确认
              </el-button>
              <el-button type="warning" size="small" @click="clearAlerts">
                清空告警
              </el-button>
            </div>
          </div>
        </template>
        <div class="alerts-list">
          <div 
            v-for="alert in alerts" 
            :key="alert.id" 
            class="alert-item"
            :class="alert.level"
          >
            <div class="alert-icon">
              <el-icon v-if="alert.level === 'critical'"><Warning /></el-icon>
              <el-icon v-else-if="alert.level === 'warning'"><InfoFilled /></el-icon>
              <el-icon v-else><Bell /></el-icon>
            </div>
            <div class="alert-content">
              <div class="alert-title">{{ alert.title }}</div>
              <div class="alert-message">{{ alert.message }}</div>
              <div class="alert-time">{{ formatDateTime(alert.timestamp) }}</div>
            </div>
            <div class="alert-actions">
              <el-button 
                size="small" 
                type="primary" 
                @click="acknowledgeAlert(alert)"
                v-if="!alert.acknowledged"
              >
                确认
              </el-button>
              <el-tag v-else type="success" size="small">已确认</el-tag>
              <el-button size="small" type="danger" @click="deleteAlert(alert)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 告警配置对话框 -->
    <el-dialog
      v-model="showAlertConfigDialog"
      title="告警配置"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="alert-config">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="CPU告警" name="cpu">
            <el-form :model="alertConfig.cpu" label-width="120px">
              <el-form-item label="启用CPU告警">
                <el-switch v-model="alertConfig.cpu.enabled" />
              </el-form-item>
              <el-form-item label="警告阈值">
                <el-input-number 
                  v-model="alertConfig.cpu.warningThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="严重阈值">
                <el-input-number 
                  v-model="alertConfig.cpu.criticalThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="持续时间">
                <el-input-number 
                  v-model="alertConfig.cpu.duration" 
                  :min="1" 
                  :max="60" 
                  :step="1"
                />
                <span class="unit">分钟</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="内存告警" name="memory">
            <el-form :model="alertConfig.memory" label-width="120px">
              <el-form-item label="启用内存告警">
                <el-switch v-model="alertConfig.memory.enabled" />
              </el-form-item>
              <el-form-item label="警告阈值">
                <el-input-number 
                  v-model="alertConfig.memory.warningThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="严重阈值">
                <el-input-number 
                  v-model="alertConfig.memory.criticalThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="持续时间">
                <el-input-number 
                  v-model="alertConfig.memory.duration" 
                  :min="1" 
                  :max="60" 
                  :step="1"
                />
                <span class="unit">分钟</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="磁盘告警" name="disk">
            <el-form :model="alertConfig.disk" label-width="120px">
              <el-form-item label="启用磁盘告警">
                <el-switch v-model="alertConfig.disk.enabled" />
              </el-form-item>
              <el-form-item label="警告阈值">
                <el-input-number 
                  v-model="alertConfig.disk.warningThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="严重阈值">
                <el-input-number 
                  v-model="alertConfig.disk.criticalThreshold" 
                  :min="0" 
                  :max="100" 
                  :step="5"
                />
                <span class="unit">%</span>
              </el-form-item>
              <el-form-item label="持续时间">
                <el-input-number 
                  v-model="alertConfig.disk.duration" 
                  :min="1" 
                  :max="60" 
                  :step="1"
                />
                <span class="unit">分钟</span>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="通知设置" name="notification">
            <el-form :model="alertConfig.notification" label-width="120px">
              <el-form-item label="邮件通知">
                <el-switch v-model="alertConfig.notification.email" />
              </el-form-item>
              <el-form-item label="邮件地址">
                <el-input v-model="alertConfig.notification.emailAddress" />
              </el-form-item>
              <el-form-item label="短信通知">
                <el-switch v-model="alertConfig.notification.sms" />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="alertConfig.notification.phoneNumber" />
              </el-form-item>
              <el-form-item label="Webhook通知">
                <el-switch v-model="alertConfig.notification.webhook" />
              </el-form-item>
              <el-form-item label="Webhook URL">
                <el-input v-model="alertConfig.notification.webhookUrl" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAlertConfigDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAlertConfig">保存配置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { 
  Monitor, Refresh, Download, Setting, Cpu, Warning, 
  InfoFilled, Bell
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const showAlertConfigDialog = ref(false)
const activeTab = ref('cpu')
const cpuTimeRange = ref('1h')
const memoryTimeRange = ref('1h')
const processSearch = ref('')
const updateTimer = ref(null)

// 系统状态数据
const systemStatus = ref({
  status: 'healthy',
  message: '系统运行正常',
  uptime: '15天 8小时 32分钟'
})

const cpuStatus = ref({
  usage: 45,
  status: 'healthy',
  message: 'CPU使用率正常'
})

const memoryStatus = ref({
  usage: 68,
  status: 'warning',
  message: '内存使用率较高'
})

const diskStatus = ref({
  usage: 82,
  status: 'critical',
  message: '磁盘空间不足'
})

const networkStatus = ref({
  connections: 156,
  inTraffic: 1024,
  outTraffic: 2048
})

const diskIOStatus = ref({
  totalIO: 1250,
  readIO: 450,
  writeIO: 800
})

// 服务数据
const services = ref([
  {
    name: 'Web服务器',
    description: 'Nginx Web服务器',
    status: 'running',
    uptime: '15天 8小时'
  },
  {
    name: '数据库服务',
    description: 'MySQL数据库服务',
    status: 'running',
    uptime: '15天 8小时'
  },
  {
    name: '应用服务',
    description: 'Node.js应用服务',
    status: 'running',
    uptime: '15天 8小时'
  },
  {
    name: '缓存服务',
    description: 'Redis缓存服务',
    status: 'stopped',
    uptime: '0天 0小时'
  }
])

// 进程数据
const processes = ref([
  { pid: 1234, name: 'nginx', cpu: 2.5, memory: 45 },
  { pid: 1235, name: 'mysql', cpu: 15.2, memory: 256 },
  { pid: 1236, name: 'node', cpu: 8.7, memory: 128 },
  { pid: 1237, name: 'redis', cpu: 1.2, memory: 32 },
  { pid: 1238, name: 'systemd', cpu: 0.5, memory: 8 }
])

// 告警数据
const alerts = ref([
  {
    id: 1,
    level: 'critical',
    title: '磁盘空间不足',
    message: '系统磁盘使用率已达到82%，建议及时清理',
    timestamp: '2024-01-15 10:30:00',
    acknowledged: false
  },
  {
    id: 2,
    level: 'warning',
    title: '内存使用率较高',
    message: '系统内存使用率达到68%，请注意监控',
    timestamp: '2024-01-15 10:25:00',
    acknowledged: false
  },
  {
    id: 3,
    level: 'info',
    title: '服务重启',
    message: 'Redis服务已自动重启',
    timestamp: '2024-01-15 10:20:00',
    acknowledged: true
  }
])

// 告警配置
const alertConfig = ref({
  cpu: {
    enabled: true,
    warningThreshold: 70,
    criticalThreshold: 90,
    duration: 5
  },
  memory: {
    enabled: true,
    warningThreshold: 75,
    criticalThreshold: 90,
    duration: 5
  },
  disk: {
    enabled: true,
    warningThreshold: 80,
    criticalThreshold: 95,
    duration: 5
  },
  notification: {
    email: true,
    emailAddress: 'admin@example.com',
    sms: false,
    phoneNumber: '',
    webhook: false,
    webhookUrl: ''
  }
})

// 计算属性
const filteredProcesses = computed(() => {
  if (!processSearch.value) return processes.value
  return processes.value.filter(process => 
    process.name.toLowerCase().includes(processSearch.value.toLowerCase())
  )
})

// 图表配置
const cpuChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: generateTimeData(cpuTimeRange.value)
  },
  yAxis: {
    type: 'value',
    max: 100,
    name: '使用率 (%)'
  },
  series: [
    {
      name: 'CPU使用率',
      type: 'line',
      smooth: true,
      data: generateCpuData(cpuTimeRange.value),
      itemStyle: { color: '#5470c6' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ]
        }
      }
    }
  ]
}))

const memoryChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: generateTimeData(memoryTimeRange.value)
  },
  yAxis: {
    type: 'value',
    max: 100,
    name: '使用率 (%)'
  },
  series: [
    {
      name: '内存使用率',
      type: 'line',
      smooth: true,
      data: generateMemoryData(memoryTimeRange.value),
      itemStyle: { color: '#91cc75' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ]
        }
      }
    }
  ]
}))

const networkChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['入站流量', '出站流量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: generateTimeData('1h')
  },
  yAxis: {
    type: 'value',
    name: '流量 (KB/s)'
  },
  series: [
    {
      name: '入站流量',
      type: 'line',
      smooth: true,
      data: generateNetworkData('in'),
      itemStyle: { color: '#5470c6' }
    },
    {
      name: '出站流量',
      type: 'line',
      smooth: true,
      data: generateNetworkData('out'),
      itemStyle: { color: '#91cc75' }
    }
  ]
}))

const diskIOChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['读取IO', '写入IO']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: generateTimeData('1h')
  },
  yAxis: {
    type: 'value',
    name: 'IO/s'
  },
  series: [
    {
      name: '读取IO',
      type: 'bar',
      data: generateDiskIOData('read'),
      itemStyle: { color: '#5470c6' }
    },
    {
      name: '写入IO',
      type: 'bar',
      data: generateDiskIOData('write'),
      itemStyle: { color: '#91cc75' }
    }
  ]
}))

// 方法
const getServiceTagType = (status) => {
  const types = {
    running: 'success',
    stopped: 'danger',
    starting: 'warning',
    stopping: 'warning'
  }
  return types[status] || 'info'
}

const getServiceStatusLabel = (status) => {
  const labels = {
    running: '运行中',
    stopped: '已停止',
    starting: '启动中',
    stopping: '停止中'
  }
  return labels[status] || status
}

const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const refreshData = () => {
  ElMessage.success('监控数据已刷新')
}

const exportReport = () => {
  ElMessage.success('监控报告导出成功')
}

const configureAlerts = () => {
  showAlertConfigDialog.value = true
}

const saveAlertConfig = () => {
  ElMessage.success('告警配置已保存')
  showAlertConfigDialog.value = false
}

const refreshServices = () => {
  ElMessage.success('服务状态已刷新')
}

const toggleService = (service) => {
  const action = service.status === 'running' ? '停止' : '启动'
  ElMessage.success(`${service.name} 服务${action}成功`)
  service.status = service.status === 'running' ? 'stopped' : 'running'
}

const viewServiceLogs = (service) => {
  ElMessage.info(`查看 ${service.name} 服务日志`)
}

const killProcess = (process) => {
  ElMessageBox.confirm(
    `确定要终止进程 ${process.name} (PID: ${process.pid}) 吗？`,
    '确认终止',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = processes.value.findIndex(p => p.pid === process.pid)
    if (index > -1) {
      processes.value.splice(index, 1)
      ElMessage.success('进程已终止')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

const acknowledgeAlert = (alert) => {
  alert.acknowledged = true
  ElMessage.success('告警已确认')
}

const deleteAlert = (alert) => {
  const index = alerts.value.findIndex(a => a.id === alert.id)
  if (index > -1) {
    alerts.value.splice(index, 1)
    ElMessage.success('告警已删除')
  }
}

const acknowledgeAllAlerts = () => {
  alerts.value.forEach(alert => {
    alert.acknowledged = true
  })
  ElMessage.success('所有告警已确认')
}

const clearAlerts = () => {
  alerts.value = []
  ElMessage.success('所有告警已清空')
}

// 数据生成函数
const generateTimeData = (range) => {
  const now = new Date()
  const data = []
  let count = 60
  
  if (range === '6h') count = 360
  if (range === '24h') count = 1440
  
  for (let i = count - 1; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60000)
    data.push(time.toLocaleTimeString('zh-CN', { hour12: false }))
  }
  
  return data
}

const generateCpuData = (range) => {
  const data = []
  let count = 60
  
  if (range === '6h') count = 360
  if (range === '24h') count = 1440
  
  for (let i = 0; i < count; i++) {
    data.push(Math.floor(Math.random() * 30) + 30) // 30-60%
  }
  
  return data
}

const generateMemoryData = (range) => {
  const data = []
  let count = 60
  
  if (range === '6h') count = 360
  if (range === '24h') count = 1440
  
  for (let i = 0; i < count; i++) {
    data.push(Math.floor(Math.random() * 20) + 60) // 60-80%
  }
  
  return data
}

const generateNetworkData = (type) => {
  const data = []
  for (let i = 0; i < 60; i++) {
    if (type === 'in') {
      data.push(Math.floor(Math.random() * 500) + 800) // 800-1300 KB/s
    } else {
      data.push(Math.floor(Math.random() * 1000) + 1500) // 1500-2500 KB/s
    }
  }
  return data
}

const generateDiskIOData = (type) => {
  const data = []
  for (let i = 0; i < 60; i++) {
    if (type === 'read') {
      data.push(Math.floor(Math.random() * 200) + 300) // 300-500 IO/s
    } else {
      data.push(Math.floor(Math.random() * 300) + 600) // 600-900 IO/s
    }
  }
  return data
}

// 定时更新数据
const startDataUpdate = () => {
  updateTimer.value = setInterval(() => {
    // 更新CPU使用率
    cpuStatus.value.usage = Math.floor(Math.random() * 30) + 30
    if (cpuStatus.value.usage > 80) {
      cpuStatus.value.status = 'critical'
      cpuStatus.value.message = 'CPU使用率过高'
    } else if (cpuStatus.value.usage > 60) {
      cpuStatus.value.status = 'warning'
      cpuStatus.value.message = 'CPU使用率较高'
    } else {
      cpuStatus.value.status = 'healthy'
      cpuStatus.value.message = 'CPU使用率正常'
    }
    
    // 更新内存使用率
    memoryStatus.value.usage = Math.floor(Math.random() * 20) + 60
    if (memoryStatus.value.usage > 85) {
      memoryStatus.value.status = 'critical'
      memoryStatus.value.message = '内存使用率过高'
    } else if (memoryStatus.value.usage > 70) {
      memoryStatus.value.status = 'warning'
      memoryStatus.value.message = '内存使用率较高'
    } else {
      memoryStatus.value.status = 'healthy'
      memoryStatus.value.message = '内存使用率正常'
    }
    
    // 更新磁盘使用率
    diskStatus.value.usage = Math.floor(Math.random() * 10) + 80
    if (diskStatus.value.usage > 90) {
      diskStatus.value.status = 'critical'
      diskStatus.value.message = '磁盘空间严重不足'
    } else if (diskStatus.value.usage > 80) {
      diskStatus.value.status = 'warning'
      diskStatus.value.message = '磁盘空间不足'
    } else {
      diskStatus.value.status = 'healthy'
      diskStatus.value.message = '磁盘空间充足'
    }
  }, 5000)
}

const stopDataUpdate = () => {
  if (updateTimer.value) {
    clearInterval(updateTimer.value)
    updateTimer.value = null
  }
}

onMounted(() => {
  startDataUpdate()
})

onUnmounted(() => {
  stopDataUpdate()
})
</script>

<style scoped>
.monitor-container {
  padding: var(--spacing-lg);
  background: var(--bg-primary);
  min-height: 100vh;
}

.page-header {
  margin-bottom: var(--spacing-xl);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.title-icon {
  font-size: 1.5rem;
  color: var(--primary-color);
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
}

/* 系统状态概览 */
.status-overview {
  margin-bottom: var(--spacing-xl);
}

.status-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.status-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.status-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  transition: all 0.3s ease;
}

.status-icon.healthy {
  background: linear-gradient(135deg, var(--success-color), var(--success-dark));
}

.status-icon.warning {
  background: linear-gradient(135deg, var(--warning-color), var(--warning-dark));
}

.status-icon.critical {
  background: linear-gradient(135deg, var(--danger-color), var(--danger-dark));
}

.status-info {
  flex: 1;
}

.status-title {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: var(--spacing-xs);
}

.status-value {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.status-desc {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

/* 性能图表 */
.performance-charts {
  margin-bottom: var(--spacing-xl);
}

.chart-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
  margin-bottom: var(--spacing-lg);
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
}

.chart-controls {
  display: flex;
  gap: var(--spacing-md);
}

.chart {
  height: 300px;
  width: 100%;
}

/* 网络和磁盘监控 */
.network-disk-monitor {
  margin-bottom: var(--spacing-xl);
}

/* 服务和进程监控 */
.services-processes {
  margin-bottom: var(--spacing-xl);
}

.service-card,
.process-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
  margin-bottom: var(--spacing-lg);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
}

.service-list,
.process-list {
  max-height: 400px;
  overflow-y: auto;
}

.service-item,
.process-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
  transition: all 0.3s ease;
}

.service-item:last-child,
.process-item:last-child {
  border-bottom: none;
}

.service-item:hover,
.process-item:hover {
  background: var(--bg-secondary);
}

.service-item.running {
  border-left: 3px solid var(--success-color);
}

.service-item.stopped {
  border-left: 3px solid var(--danger-color);
}

.service-info,
.process-info {
  flex: 1;
}

.service-name,
.process-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.service-desc {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

.process-pid {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

.service-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-xs);
}

.service-uptime {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

.process-metrics {
  display: flex;
  gap: var(--spacing-md);
}

.metric {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-xs);
}

.metric-label {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

.metric-value {
  font-weight: 500;
  color: var(--text-primary);
}

.service-actions,
.process-actions {
  display: flex;
  gap: var(--spacing-sm);
}

/* 告警信息 */
.alerts-section {
  margin-bottom: var(--spacing-xl);
}

.alerts-card {
  border-radius: var(--radius-lg);
}

.alert-controls {
  display: flex;
  gap: var(--spacing-md);
}

.alerts-list {
  max-height: 400px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
  transition: all 0.3s ease;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-item:hover {
  background: var(--bg-secondary);
}

.alert-item.critical {
  border-left: 3px solid var(--danger-color);
  background: rgba(245, 108, 108, 0.05);
}

.alert-item.warning {
  border-left: 3px solid var(--warning-color);
  background: rgba(251, 191, 36, 0.05);
}

.alert-item.info {
  border-left: 3px solid var(--primary-color);
  background: rgba(59, 130, 246, 0.05);
}

.alert-icon {
  font-size: 1.2rem;
  color: var(--primary-color);
}

.alert-item.critical .alert-icon {
  color: var(--danger-color);
}

.alert-item.warning .alert-icon {
  color: var(--warning-color);
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.alert-message {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: var(--spacing-xs);
}

.alert-time {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

.alert-actions {
  display: flex;
  gap: var(--spacing-sm);
}

/* 告警配置对话框 */
.alert-config {
  padding: var(--spacing-lg) 0;
}

.unit {
  margin-left: var(--spacing-sm);
  color: var(--text-secondary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .monitor-container {
    padding: var(--spacing-md);
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .status-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .status-icon {
    width: 50px;
    height: 50px;
    font-size: 1.25rem;
  }

  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .service-item,
  .process-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }

  .service-status,
  .process-metrics {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
  }

  .service-actions,
  .process-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .alert-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }

  .alert-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }

  .status-value {
    font-size: 1.25rem;
  }

  .chart {
    height: 200px;
  }
}
</style>
